Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
Why does "this" change when passing a function as a call back?

I have these 2 objects:

var Foo = function () {
    this.name = 'foo';
};

Foo.prototype.sayName = function () {
    console.log(this.name);
};
var Bar = function () {
    this.cb = null;
};

Bar.prototype.setCb = function (cb) {
    this.cb = cb;
};

Bar.prototype.callCb = function () {
    this.cb();
};

And I have this result:

var foo = new Foo();
var bar = new Bar();

foo.sayName();  // "foo"
bar.setCb(foo.sayName);
bar.callCb();   // undefined

This happens because when we call foo.sayName inside Bar, this is pointing to the Bar object. Can someone explain what's happening here?

I also noticed that I can circumvent this by instead passing in an anonymous function bar.setCb(function() {foo.sayName();});. Are there other/better ways around this problem?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is the part of Javascript that most throws people coming from another language.

Basically, the this pointer is set at the time of the call. When you pull a function off an object, you just get the function, not the context in which it came from (the object it came from). This is unlike for example Python with its bound method objects.

In fact, if you did something like:

let sayName = foo.sayName
sayName()

that would also throw with an "undefined" exception, since calling it that way you lose which object you're calling the method on.

So how do you work around this? There's a couple of options, both of which involve capturing that context.

The first you can do, as the comment suggested, would be to use an arrow function:

bar.setCb(() => foo.sayName())

This "captures" the object to call the function on.

Another option would be to use the Function.bind function:

bar.setCb(foo.sayName.bind(foo))

This creates a new function instance that has it's this pointer set to foo.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda